#include <math.h>
#include <time.h>
#include <string>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <unistd.h>
#include <stddef.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <linux/un.h>
#include <sys/stat.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/syscall.h>

#define SOCK_QEMU_PATH    "@/tmp/mcu_qemu"

int main(int argc, char **argv)
{
	struct sockaddr_un ssockaddr;
    struct sockaddr_un csockaddr;
    int32_t ssockfd = 0;
    int32_t csockfd = 0;
    int32_t ssize = 0;
    socklen_t csize = 0;
    int32_t nread = 0;
    uint8_t buff[1024];
    char sockname[1024];
    memset(sockname, 0, 1024);

    ssockfd = socket(AF_UNIX, SOCK_STREAM, 0);

    ssockaddr.sun_family = AF_UNIX;
    sprintf(sockname, "%s", SOCK_QEMU_PATH);
    strcpy(ssockaddr.sun_path, sockname);
    ssockaddr.sun_path[0] = 0;
    ssize = offsetof(struct sockaddr_un, sun_path) + strlen(sockname);

    bind(ssockfd, (struct sockaddr *)&ssockaddr, ssize);
    listen(ssockfd, 5);

    csize = sizeof(csockaddr);
    while (1)
    {
        memset(buff, 0, 1024);
        if (csockfd == 0) {
            csockfd = accept(ssockfd, (struct sockaddr *)&csockaddr,&csize);
        }

        //read data form socket
        nread = read(csockfd, buff, 1024);
        if (nread == 0) {
            close(csockfd);
            csockfd = 0;
            continue;
        } else if (nread < 0) {
            if (errno != EWOULDBLOCK) {
                close(csockfd);
                csockfd = 0;
            }
            continue;
        }
		
		printf("recv: %s\n", buff);
	}
}